package com.wzy.oa_sys.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.wzy.oa_sys.config.ObjectConfig;
import com.wzy.oa_sys.mapper.user.DeptMapper;
import com.wzy.oa_sys.mapper.user.UserMapper;
import com.wzy.oa_sys.model.pojo.user.OaDept;
import com.wzy.oa_sys.model.pojo.user.OaUser;
import com.wzy.oa_sys.model.request.user.PasswordReq;
import com.wzy.oa_sys.model.request.user.UserReq;
import com.wzy.oa_sys.model.response.user.UserResp;
import com.wzy.oa_sys.model.response.user.UserRespForTask;
import com.wzy.oa_sys.service.user.DeptService;
import com.wzy.oa_sys.service.user.PositionService;
import com.wzy.oa_sys.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, OaUser>  implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private PositionService positionService;
    private static final String letters = "abcdefghijklmnopqrstuvwxyz"; // 小写字母
    private static final String digits = "0123456789"; // 数字
    private static final int ID_LENGTH = 10; // ID 长度为 10 位

    @Override
    public List<UserResp> getUserList() {
        List<OaUser> oaUsers = userMapper.selectList(null);
        List<UserResp> userResps = new ArrayList<>();
        oaUsers.forEach(oaUser -> {
            UserResp user = UserResp.builder()
                    .id(oaUser.getNUserId())
//                    .username(oaUser.getCUserName())
                    .realname(oaUser.getCRealName())
                    .gender(oaUser.getCGender())
                    .autoid(oaUser.getCAutoUserId())
                    .tel(oaUser.getCPhone())
                    .birth(oaUser.getDtBirth())
                    .bankcard(oaUser.getCBank())
                    .joinDate(oaUser.getDtTime())
                    .img(oaUser.getCImgPath()).build();
            if(!ObjectConfig.isEmpty(deptService.getDeptById(oaUser.getNDeptId()))){
                user.setDeptname(deptService.getDeptById(oaUser.getNDeptId()).getCDeptName());
            }
            if(!ObjectConfig.isEmpty(positionService.getPositionById(oaUser.getNPositionId()))){
                user.setPosition(positionService.getPositionById(oaUser.getNPositionId()).getCPosition());
            }
            //角色
            if(oaUser.getNRole() == 0){
                user.setRole("普通员工");
            }else if(oaUser.getNRole() == 1){
                user.setRole("超级管理员");
            }else if(oaUser.getNRole() == 2){
                user.setRole("普通管理员");
            }
            //查询上级
            if(oaUser.getNFatherId() != 0){
                if(!ObjectConfig.isEmpty(userMapper.selectUserById(oaUser.getNFatherId()))){
                    user.setSuperior(userMapper.selectUserById(oaUser.getNFatherId()).getCRealName());
                }
            }
            if(oaUser.getNType() == 1){
                user.setEmployeeType("正式");
            }else if(oaUser.getNType() == 2){
                user.setEmployeeType("外包");
            }else if(oaUser.getNType() == 3){
                user.setEmployeeType("实习");
            }
            userResps.add(user);

        });
        return userResps;
    }

    @Override
    public OaUser getUserById(long id) {
        return userMapper.selectById(id);
    }



    @Override
    public List<UserResp> getUserByDeptId(long deptId) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_dept_id",deptId);
        List<OaUser> oaUsers = userMapper.selectList(queryWrapper);
        List<UserResp> userResps = new ArrayList<>();
        oaUsers.forEach(oaUser -> {
            UserResp user = UserResp.builder()
                    .id(oaUser.getNUserId())
                    .username(oaUser.getCUserName())
                    .realname(oaUser.getCRealName())
                    .tel(oaUser.getCPhone()).build();
            if(!ObjectConfig.isEmpty(deptService.getDeptById(oaUser.getNDeptId()))){
                user.setDeptname(deptService.getDeptById(oaUser.getNDeptId()).getCDeptName());
            }
            if(!ObjectConfig.isEmpty(positionService.getPositionById(oaUser.getNPositionId()))){
                user.setPosition(positionService.getPositionById(oaUser.getNPositionId()).getCPosition());
            }
            userResps.add(user);
        });
        return userResps;
    }

    @Override
    public List<UserResp> getAdminList() {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_role",1);
        List<OaUser> oaUsers = userMapper.selectList(queryWrapper);
        List<UserResp> userResps = new ArrayList<>();
        oaUsers.forEach(oaUser -> {
            UserResp user = UserResp.builder()
                    .id(oaUser.getNUserId())
                    .username(oaUser.getCUserName())
                    .realname(oaUser.getCRealName())
                    .tel(oaUser.getCPhone()).build();
            if(!ObjectConfig.isEmpty(deptService.getDeptById(oaUser.getNDeptId()))){
                user.setDeptname(deptService.getDeptById(oaUser.getNDeptId()).getCDeptName());
            }
            if(!ObjectConfig.isEmpty(positionService.getPositionById(oaUser.getNPositionId()))){
                user.setPosition(positionService.getPositionById(oaUser.getNPositionId()).getCPosition());
            }
            userResps.add(user);
        });
        return userResps;
    }

    @Override
    public int deleteUserById(Integer id) {
        int i = userMapper.deleteUserById(id);
        return i;
    }

    @Override
    public UserResp getUserDetialById(Integer id) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id",id);
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        UserResp user = UserResp.builder()
                .id(oaUser.getNUserId())
                .username(oaUser.getCUserName())
                .realname(oaUser.getCRealName())
                .gender(oaUser.getCGender())
                .tel(oaUser.getCPhone())
                .bankcard(oaUser.getCBank())
                .img(oaUser.getCImgPath())
                .autoid(oaUser.getCAutoUserId())
                .typeId(oaUser.getNType())
                .roleId(oaUser.getNRole())
                .joinDate(oaUser.getDtTime())
                .build();
        if(oaUser.getDtBirth() != null){
            user.setBirth(oaUser.getDtBirth());
        }
        //角色
        if(oaUser.getNRole() == 0){
            user.setRole("普通员工");
        }else if(oaUser.getNRole() == 1){
            user.setRole("超级管理员");
        }else if(oaUser.getNRole() == 2){
            user.setRole("普通管理员");
        }
        if(oaUser.getNType() == 1){
            user.setEmployeeType("正式");
        }else if(oaUser.getNType() == 2){
            user.setEmployeeType("外包");
        }else if(oaUser.getNType() == 3){
            user.setEmployeeType("实习");
        }

        if(!ObjectConfig.isEmpty(deptService.getDeptById(oaUser.getNDeptId()))){
            user.setDeptname(deptService.getDeptById(oaUser.getNDeptId()).getCDeptName());
        }
        if(!ObjectConfig.isEmpty(positionService.getPositionById(oaUser.getNPositionId()))){
            user.setPosition(positionService.getPositionById(oaUser.getNPositionId()).getCPosition());
        }
        //查询上级
        if(oaUser.getNFatherId() != 0){
            if(!ObjectConfig.isEmpty(userMapper.selectUserById(oaUser.getNFatherId()))){
                user.setSuperior(userMapper.selectUserById(oaUser.getNFatherId()).getCRealName());
            }
        }


        return user;
    }

    @Override
    public List<UserResp> getNotDeptManagerList() {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_dept_head",0);
        queryWrapper.eq("n_type",1);
        //正式且不为部门负责人
        List<OaUser> oaUsers = userMapper.selectList(queryWrapper);
        List<UserResp> userResp = new ArrayList<>();
        oaUsers.forEach(oaUser -> {
           userResp.add(UserResp.builder()
                   .id(oaUser.getNUserId())
                   .realname(oaUser.getCRealName()).build());
        });
        return userResp;
    }

    @Override
    public List<UserResp> getDeptManagerList() {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_dept_head","1");
        List<OaUser> oaUsers = userMapper.selectList(queryWrapper);
        List<UserResp> userResp = new ArrayList<>();
        oaUsers.forEach(oaUser -> {
            userResp.add(UserResp.builder()
                   .id(oaUser.getNUserId())
                   .realname(oaUser.getCRealName()).build());
        });
        return userResp;
    }

    @Override
    public List<UserRespForTask> getChargeList() {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_role",1).or().eq("n_role",2);
        List<OaUser> oaUsers = userMapper.selectList(queryWrapper);
        List<UserRespForTask> userResp = new ArrayList<>();
        //获得所有部门的负责人
        Set<Long> managerIds = new HashSet<>();
        deptMapper.selectList(null).forEach(dept -> {managerIds.add(dept.getNManagerId());});
        oaUsers.forEach(oaUser -> {
            UserRespForTask build = UserRespForTask.builder()
                    .id(oaUser.getNUserId())
                    .realname(oaUser.getCRealName())
                    .role(oaUser.getNRole())
                    .build();
            //如果为部门负责人，则添加部门ID
            if(managerIds.contains(oaUser.getNUserId())){
                QueryWrapper<OaDept> deptQueryWrapper = new QueryWrapper<>();
                deptQueryWrapper.eq("n_manager_id",oaUser.getNUserId());
                OaDept dept = deptMapper.selectOne(deptQueryWrapper);
                build.setDeptId(dept.getNDeptId());
            }
            userResp.add(build);
        });
        return userResp;
    }

    @Override
    public void addUser(UserReq userReq) {
        OaUser oaUser = new OaUser();
        oaUser.setNDeptId(userReq.getDeptname());
        oaUser.setCUserName(userReq.getUsername());
        oaUser.setCRealName(userReq.getRealname());
        oaUser.setCGender(userReq.getGender());
        oaUser.setCAccount(userReq.getAccount());
        //新增默认密码为oa123456
        String password = encryptPassword("123456");
        oaUser.setCPassword(password);
        oaUser.setNPositionId(userReq.getPosition());
        oaUser.setCPhone(userReq.getTel());
        oaUser.setNRole(userReq.getRole());
        oaUser.setNFatherId(userReq.getSuperior());
        oaUser.setNType(userReq.getEmployeeType());
        oaUser.setDtTime(userReq.getJoinDate());
        oaUser.setCAutoUserId(generateUniqueId());
//        oaUser.setCCountry();
//        oaUser.setCCity();
        userMapper.insert(oaUser);
    }

    //MD5加密密码
    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] byteData = md.digest();

            // Convert the byte to hex format
            StringBuilder sb = new StringBuilder();
            for (byte b : byteData) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error encrypting password", e);
        }
    }


    @Override
    public void updateUser(UserReq userReq) {
        System.out.println(userReq);
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id",userReq.getId());
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        System.out.println(oaUser);
        if(userReq.getDeptname()!=0){
            oaUser.setNDeptId(userReq.getDeptname());
        }
        if(userReq.getRealname()!=null&&userReq.getRealname().length()>0){
            oaUser.setCRealName(userReq.getRealname());
        }
        if(userReq.getGender()!=null&&userReq.getGender().length()>0){
            oaUser.setCGender(userReq.getGender());
        }
        if(userReq.getPosition()!=0){
            oaUser.setNPositionId(userReq.getPosition());
        }
        if(userReq.getTel()!=null&&userReq.getTel().length()>0){
            oaUser.setCPhone(userReq.getTel());
        }
        oaUser.setNRole(userReq.getRole());
        if(userReq.getSuperior()!=0){
            oaUser.setNFatherId(userReq.getSuperior());
        }
        if(userReq.getEmployeeType()!=0){
            oaUser.setNType(userReq.getEmployeeType());
        }
        oaUser.setDtTime(userReq.getJoinDate());
        userMapper.update(oaUser,queryWrapper);
    }

    @Override
    public void updateUserPassword(long id) {
        String password = encryptPassword("123456");
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id",id);
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        if(oaUser!=null){
            oaUser.setCPassword(password);
            userMapper.update(oaUser,queryWrapper);
        }
    }

    @Override
    public void updateMyDetail(UserResp userResp) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id",userResp.getId());
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        boolean flag = false;
        if(oaUser!=null){
            if(userResp.getRealname()!=null&&!userResp.getRealname().equals(oaUser.getCRealName())){
                oaUser.setCRealName(userResp.getRealname());
                flag = true;
            }
            if(userResp.getGender()!=null&&!userResp.getGender().equals(oaUser.getCGender())){
                oaUser.setCGender(userResp.getGender());
                flag = true;
            }
            if(userResp.getTel()!=null&&!userResp.getTel().equals(oaUser.getCPhone())){
                oaUser.setCPhone(userResp.getTel());
                flag = true;
            }
            if(userResp.getBankcard()!=null&&!userResp.getBankcard().equals(oaUser.getCBank())){
                oaUser.setCBank(userResp.getBankcard());
                flag = true;
            }
            if(userResp.getBirth()!=null&&!userResp.getBirth().equals(oaUser.getDtBirth())){
                oaUser.setDtBirth(userResp.getBirth());
                flag = true;
            }

            if(flag){
                userMapper.update(oaUser,queryWrapper);
            }

        }
    }

    @Override
    public void updatePassword(PasswordReq passwordReq) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_account",passwordReq.getAccount());
        queryWrapper.eq("c_password",encryptPassword(passwordReq.getOldPassword()));
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        if(oaUser!=null){
            String newPassword = encryptPassword(passwordReq.getNewPassword());
            oaUser.setCPassword(newPassword);
            userMapper.update(oaUser,queryWrapper);
        }
    }

    @Override
    public UserResp getFather(Long userId) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id",userId);
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        QueryWrapper<OaUser> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("n_user_id",oaUser.getNFatherId());
        if(userMapper.selectOne(queryWrapper2)!=null){
            OaUser oaUser2 = userMapper.selectOne(queryWrapper2);
            UserResp userResp = UserResp.builder().realname(oaUser2.getCRealName()).id(oaUser2.getNUserId()).build();
            return userResp;
        }
        return null;
    }


    // 生成随机不重复的 ID
    public String generateUniqueId() {
        Random random = new Random();
        StringBuilder id = new StringBuilder(ID_LENGTH);

        // 生成小写字母部分
        for (int i = 0; i < 3; i++) {
            int index = random.nextInt(letters.length());
            id.append(letters.charAt(index));
        }

        // 生成数字部分
        for (int i = 0; i < 7; i++) {
            int index = random.nextInt(digits.length());
            id.append(digits.charAt(index));
        }

        // 随机打乱 ID 字符顺序
        List<Character> characters = new ArrayList<>();
        for (char ch : id.toString().toCharArray()) {
            characters.add(ch);
        }
        Collections.shuffle(characters);

        // 重组 ID
        StringBuilder shuffledId = new StringBuilder(ID_LENGTH);
        for (char ch : characters) {
            shuffledId.append(ch);
        }
        Set<String> generatedIds = new HashSet<>();
        userMapper.selectList(null).forEach(user -> generatedIds.add(user.getCAutoUserId()));
        // 检查 ID 是否已经存在
        String uniqueId = shuffledId.toString();
        if (!generatedIds.contains(uniqueId)) {
            generatedIds.add(uniqueId);
            return uniqueId;
        } else {
            // 如果 ID 已存在，递归调用以生成新的 ID
            return generateUniqueId();
        }
    }
}
